package com.example.shopping.controller;

import com.example.shopping.entity.Category;
import com.example.shopping.entity.Goods;
import com.example.shopping.entity.User;
import com.example.shopping.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {

    private static int pageSize = 5;

    @Autowired
    AdminService adminService;
    @Autowired
    UserService userService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    MinioService minioService;

    @GetMapping("")
    public String admin(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user == null || !"admin".equals(user.getAccount())) {
            return "redirect:/";//不是管理员不能进入
        }
        return "admin";
    }

    @GetMapping("/goods/add")
    public String goodadd(Model model) {
        List<Category> list = categoryService.getAll();
        model.addAttribute("categories", list);
        return "goods_add";
    }

    @PostMapping("/goods/add")
    public String addGoods(Goods good) {
        boolean b = goodsService.insertGood(good);
        return "redirect:/";
    }

    @PostMapping("/upload/good")
    @ResponseBody
    public String uploadGood(@RequestParam MultipartFile file, Model model, HttpSession session) throws Exception {
        User user = (User) session.getAttribute("loginUser");
        if (user == null || !user.getAccount().equals("admin")) {
            return "redirect:/user/login";
        }
        //调用Service方法上传到minio
        String url = minioService.uploadFile(file);
        model.addAttribute("url", url);
        return url;
    }

    //进入普通用户管理列表
    @GetMapping("/user/list")
    public String userList(Model model, @RequestParam(defaultValue = "1") int page) {
        long total = adminService.count();
        // 计算总页数
        int totalPages = (int) Math.ceil((double) total / pageSize);
        // 确保页码在有效范围内
        if (page < 1) {
            page = 1;
        }
        if (page > totalPages) {
            page = totalPages;
        }
        //拿到第page页的用户列表
        List<User> userlist = adminService.getAllUserByPage(page, pageSize);

        model.addAttribute("userlist", userlist);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("total", total);
        return "admin_list";
    }

    @GetMapping("/user/freeze")
    public String freeze(@RequestParam Integer id) {
        boolean success = userService.freezeUser(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/user/unfreeze")
    public String unfreeze(@RequestParam Integer id) {
        boolean success = userService.unfreezeUser(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/user/blacklist/add")
    public String addToBlacklist(@RequestParam Integer id) {
        boolean success = userService.addToBlacklist(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/user/blacklist/remove")
    public String removeFromBlacklist(@RequestParam Integer id) {
        boolean success = userService.removeFromBlacklist(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/user/delete")
    public String delete(@RequestParam Integer id) {
        boolean success = userService.deleteUser(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/category/list")
    public String categoryList(Model model) {
        List<Category> all = categoryService.getAll();
        model.addAttribute("categories", all);
        return "category_list";
    }

    @GetMapping("/category/add")
    public String categoryList() {
        return "category_add";
    }

    @PostMapping("/category/add")
    public String categoryAdd(@RequestParam String name, @RequestParam(required = false, defaultValue = "0") Integer pid) {
        Category category = new Category();
        category.setName(name);
        category.setPid(pid);
        boolean b = categoryService.insert(category);
        if (!b) {
            //添加不超过就重定向回添加界面，这里不成功的原因大概率是类别名重复，或者是类别名不符合规则
            return "redirect:/admin/category/add";
        }
        //成功就回到列表界面
        return "redirect:/admin/category/list";
    }

    //安全退出
    @GetMapping("/logout") // /user/logout
    public String loginout(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user != null) {
            session.removeAttribute("loginUser");//删除登录数据
            userService.logout(user.getId());
        }

        return "redirect:/";
    }
}
